package cn.jorian.framework.service.impl;

import cn.jorian.framework.bean.ResponseResult;
import cn.jorian.framework.net.NetManager;
import cn.jorian.framework.service.IUploadService;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class UploadFileServiceImpl implements IUploadService {

    @Override
    public void uploadFile() {
        String fileName = "test.txt";
        FileSystemResource fileSystemResource = createFile("文件内容", fileName);

        RequestBody nameBody = RequestBody.create(MediaType.parse("multipart/form-data"), "hello,retrofit");
        RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), fileSystemResource.getFile());
        Map<String, RequestBody> map = new HashMap<>();
        map.put("name", nameBody);
        //这里的key必须这么写，否则服务端无法识别
        map.put("file\"; filename=\""+ fileName, fileBody);

        NetManager.newInstance().getServiceApi().uploadFile(map).enqueue(new Callback<ResponseResult>() {
            @Override
            public void onResponse(Call<ResponseResult> call, Response<ResponseResult> response) {

            }

            @Override
            public void onFailure(Call<ResponseResult> call, Throwable throwable) {

            }
        });
    }

    private FileSystemResource createFile(String msg, String fileName) {
        //创建BufferedWriter对象,构造方法中传递FileWriter对象
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(fileName));
            bw.write(msg);
            bw.flush();
            //释放资源
            bw.close();
            FileSystemResource file = new FileSystemResource(new File(fileName));
            return file;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
